import socket,platform
import os
import re
# 特定端口
sysPort = 22001
pid = 0
if platform.system() == "Windows":
    command = f'netstat -ano | findstr {sysPort}'
    command_read = os.popen(command).read()
    pid = os.popen(command).read().split('\n')[0].split()[-1]
else:
    command = f"lsof -i:{sysPort} -F -n | grep 'p'"
    output = os.popen(command).read().split('\n')[0]
    pid = output[1:]


    # 提取进程 ID 和端口号的正则表达式

    # 使用正则表达式提取进程 ID 和端口号
    # match = re.search(pattern, output)

# if command_read == '':
#    print(f"未找到端口{sysPort}")
#    exit()
print(f"pid = {pid}")

if  not  re.search(r'(\d+)', pid):
    print(f"未找到端口{sysPort}对应的进程")
    exit()
else:
    pid = int(pid)

print(pid, type(pid))


try:
    if platform.system() == "Windows":
        command = 'taskkill /f /t /pid %s' % pid
    else:
        command = f'kill -9 {pid}'

    os.system(command)
    print(f'{command}成功！！！')
except Exception as e:
    print(f'关闭chrome进程失败,error:{e}')